//
//  AppDelegate.m
//  HubeiHotel
//
//  Created by 张露杰 on 17/11/7.
//  Copyright © 2017年 张露杰. All rights reserved.
//

#import "AppDelegate.h"
#import "HBHLoginViewController.h"
#import "HBHTabBarViewController.h"
#import "NSArray+index.h"
@interface AppDelegate ()<BMKGeneralDelegate>

@property (nonatomic, strong) BMKMapManager *mapManager;

@end

@implementation AppDelegate

-(void)saveCityData//缓存省市区 排序
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSArray *suoyinArr = [standfault objectForKey:@"cityArr"];
        if (suoyinArr.count<=0) {//suoyinArr 有数据就则已经加载过
            NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"City_BHHotel" ofType:@"plist"]];
            suoyinArr = [NSArray suoyin:array];
            //将A到Z排序存在本地以免卡顿几秒
            [standfault setObject:suoyinArr forKey:@"cityArr"];
            [standfault synchronize];
        }
    });
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"T5wWkAab8Ar1DBsw4QVB2yGmC4QvWjyn" generalDelegate:self];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    [WXApi registerApp:WXAppKey enableMTA:YES];
    
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [UINavigationBar appearance].barTintColor = [UIColor whiteColor];
    [UINavigationBar appearance].translucent = NO;
    self.window.rootViewController = [HBHTabBarViewController new];
    [self getVersionDetails];
    return YES;
}

-(void)getVersionDetails
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [HttpRequest PostrequestUrl:@"/other/versionInfo" Dic:@{@"id":@"1"} completion:^(NSDictionary *responseDic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"responseDic:%@",responseDic);
                if ([responseDic[@"success"] boolValue]) {
                    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
                    if (![responseDic[@"data"][@"varsionCode"] isEqualToString:[NSString stringWithFormat:@"%@",[infoDictionary objectForKey:@"CFBundleShortVersionString"]]]) {
                        UIAlertController*alertController = [UIAlertController alertControllerWithTitle:@"有新版本发布哦，快去更新" message:nil preferredStyle:UIAlertControllerStyleAlert];
                        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction*_Nonnullaction) {
                        }]];
                        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction*_Nonnullaction) {
                           [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/hb%E9%85%92%E5%BA%97%E7%BD%91/id1319038896?mt=8"]];
                        }]];
                        [[TomamaUI getTopVC] presentViewController:alertController animated:YES completion:^{
                        }];
                    }
                }
            });
        }];
    });
}


-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    if ([url.scheme isEqualToString:WXAppKey]) {
        return [WXApi handleOpenURL:url delegate:self];
    }else if ([url.scheme isEqualToString:[NSString stringWithFormat:@"tencent%@",QQKey]]){
        return [TencentOAuth HandleOpenURL:url];
    }else if ([url.host isEqualToString:@"pay"])
    {   //跳转微信
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if ([url.scheme isEqualToString:WXAppKey]) {
        return [WXApi handleOpenURL:url delegate:self];
    }else if ([url.scheme isEqualToString:[NSString stringWithFormat:@"tencent%@",QQKey]]){
        return [TencentOAuth HandleOpenURL:url];
    }else if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"result = %@",resultDic);
//        }];
    }else if ([url.host isEqualToString:@"pay"])
    {   //跳转微信
        return [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.scheme isEqualToString:WXAppKey]) {
        [WXApi handleOpenURL:url delegate:self];
    }
    if ([url.host isEqualToString:@"pay"])
    {   //跳转微信
        return [WXApi handleOpenURL:url delegate:self];
    }
    if ([url.scheme isEqualToString:[NSString stringWithFormat:@"tencent%@",QQKey]]) {
        return [TencentOAuth HandleOpenURL:url];
    }
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付，处理支付结果
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
////            NSLog(@"result = %@",resultDic);
//        }];
    }
    return YES;
}

-(void)onResp:(BaseResp*)resp{
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *authResp = (SendAuthResp *)resp;
        NSLog(@"%@=======%@",authResp.code,authResp.state);
        [[NSNotificationCenter defaultCenter]postNotificationName:LoginNotification object:@{@"wxLogin":[NSString stringWithFormat:@"%d",resp.errCode]}];
    }else if ([resp isKindOfClass:[PayResp class]])
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:PayNotification object:@{@"wxPay":[NSString stringWithFormat:@"%d",resp.errCode]}];
    }else if ([resp isKindOfClass:[SendMessageToWXResp class]]){
        SendMessageToWXResp *sendResp = (SendMessageToWXResp *)resp;
        [[NSNotificationCenter defaultCenter]postNotificationName:WXShareNotification object:@{@"wxShare":[NSString stringWithFormat:@"%d",sendResp.errCode]}];
    }
    if ([resp isKindOfClass:[SendMessageToQQResp class]]) {
        SendMessageToQQResp * QQResp = (SendMessageToQQResp *)resp;
        [[NSNotificationCenter defaultCenter]postNotificationName:QQShareNotification object:@{@"qqShare":[NSString stringWithFormat:@"%ld",(long)[QQResp.result integerValue]]}];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
